import itchat
import requests
import time
import re
import os
import shutil
# from urllib.request import urlretrieve
import urllib.request
from urllib.parse import quote
import string

def get_info(message):
    try:
        apiUrl = "http://api.qingyunke.com/api.php?key=free&appid=0&msg="
        r = requests.post(apiUrl+message).json()
        info = r['content']
        print("robot reply:%s" % info)
        return info
    except:
        return  

def get_tuling_response(msg):
    tulingApiUrl = 'http://www.tuling123.com/openapi/api'   #改成你自己的图灵机器人的api，上图红框中的内容，不过用我的也无所谓，只是每天自动回复的消息条数有限
    # a16d8a3d03db4ea9b93438478672a639
    # 0ac56da4f87641d2a412ea4ae3bb711f
    data = {
        'key': '0ac56da4f87641d2a412ea4ae3bb711f',  # Tuling Key
        'info': msg,  # 这是我们发出去的消息
        'userid': 'wechat-robot',  # 这里你想改什么都可以
    }
    # 我们通过如下命令发送一个post请求
    r = requests.post(tulingApiUrl, data=data).json()
    return r.get('text')


appoUrl = "https://fxappoj.gangcai.store:4334/api/nt/appo/appointments"
def appo_lists(message):
    try:
        params = '?limit=100&page=1&labeled=有'
        r = requests.get(appoUrl+'/list2'+params).json()
        infos = r['data']
        strs = ''
        a_list = []
        for info in infos:
            strs = assemble_info(info)['strs']+ '\r\n'
            a_list.append(strs)
        # print("robot reply:%s" % strs)
        # print(a_list)
        return a_list
    except:
        return

def random_appo_list():
    try:
        r = requests.post(appoUrl+'/randomInfo').json()
        info = r['data']
        strs = assemble_info(info)['strs']
        return strs
    except:
        return

def appo_info_by_code(code):
    try:
        params = '?code=TS-'+code
        r = requests.post(appoUrl+'/infoByCode'+params).json()
        info = r['data']
        return assemble_info(info)
    except:
        return

def assemble_info(info):
    strs_txt = {'strs': '', 'photoes': ''}
    strs = ''
    selfSituation_copy = ''
    gender = '男'
    onlySon = '独生'
    if info['selfSituation'] != '':
        selfSituation_copy = '自身情况: ' + info['selfSituation'] + '\r\n'
    if info['gender'] == 2:
        gender = '女'
    if info['onlySon'] == 2:
        onlySon = '非独生'
    strs += '' + info['bCode'] + '\r\n'
    strs += '婚姻: ' + info['marriage'] + '\r\n'
    strs += '性别: ' + gender + '  ' + onlySon + '\r\n'
    strs += '生日: ' + info['birthday'][:4] + '  ' + '\r\n'
    strs += '身高/体重: ' + str(info['height']) + '/' + str(info['weight']) + '\r\n'
    strs += '学历/职业: ' + info['education'] + '/' + info['occupation'] + info['salary'] + '万/年\r\n'
    strs += '房车: ' + info['house'] + '/' + info['car'] + '\r\n'
    strs += '籍贯: ' + info['nativePlace'] + '\r\n'
    strs += '居住: ' + info['liveCity'] + '\r\n'
    strs += '爱好: ' + info['hobby'] + '\r\n'
    strs += selfSituation_copy
    strs += '父母情况: ' + info['parentsSituation'] + '\r\n'
    strs += '择偶要求: ' + info['requirements']
    strs_txt['strs'] = strs
    strs_txt['photoes'] = info['photo']
    return strs_txt

locale_txt = {"txt": "", "dateTime": time.time(), "count": 1,"msgCount": 1, "loop_time": time.time()}
def record_txt(*args):
    msg_text = args[0].strip()
    locale_text = locale_txt["txt"]
    count = time.time() - locale_txt["dateTime"]
    num_reg = re.search(r'\d{2,4}', msg_text)
    male_reg = re.search(r'(男|女)', msg_text)
    keyword_not_in_reg = re.search(r'有没有|引用|- - -|@|接龙|东钱湖万金社区|公益|义务|相亲|陆埠|新浦|临山|范市|掌起|白沙|横河|浒山|逍林|周巷|观海', msg_text)
    phone_reg = re.search(r'(((13[0-9]{1})|(14[57]{1})|(15[012356789]{1})|(17[03678]{1})|(18[0-9]{1})|(19[89]{1})|(16[6]{1}))+\d{8})', msg_text)
    if str(num_reg) != 'None' and str(male_reg) != 'None' and str(keyword_not_in_reg) == 'None' and str(phone_reg) == 'None':
        if count > 1800:
            locale_txt["txt"] = ""
            locale_txt["dateTime"] = time.time()
            locale_txt["msgCount"] = 1
        if msg_text not in locale_text:
            locale_txt["txt"] = locale_text+msg_text
            return True
        else:
            return False
    else:
         return False

def loop_random_info(my_room):
    count = time.time() - locale_txt["loop_time"]
    # 单位秒  一小时6条
    if count > 600:
        locale_txt["loop_time"] = time.time()
        re_txt = random_appo_list()
        for room in my_room:
            room_nick_name = room['NickName']
            if '天上闲人地上仙资料' == room_nick_name:
                username = room['UserName']
                itchat.send_msg(re_txt, username)




@itchat.msg_register([itchat.content.TEXT], isGroupChat=True)
def print_group_msg(msg):
    try:
        localtime = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time()))
        g_name = ''
        my_room = itchat.search_chatrooms(name=g_name)  # 传入指定群名进行搜索，之所以搜索，是因为群员的名称信息也在里面
        current_room_id = msg['FromUserName']
        current_room_name = ''
        for room in my_room:
            if current_room_id == room['UserName']:
                current_room_name = room['NickName']
                break
        msg_text = msg['Text']
        # msg_text = msg_text.replace("东钱湖万金社区", "")
        print("%s  %s  %s:  %s" % (current_room_name, localtime, msg['ActualNickName'], msg_text))

        # my_room = itchat.get_chatrooms(update=True)  # 获取所有群的相关信息，update=True表示信息更新
        current_room_name_reg = re.search(r'情缘|心缘|有缘|结缘|牵缘|牵线|红娘群|对接群|结对群|相亲群|再婚|琼台月老|龙凤呈祥|圆缘|男女|爱之心|余慈|余姚相亲介绍|百合|婚介|未婚|老三区公益|三江缘|甬爱驿站', current_room_name)

        #if str(current_room_name_reg) != 'None' and 235901 > int(time.strftime("%H%M%S")) > 10101:  # 上午6点到晚上23点  加叮嘱:
        if str(current_room_name_reg) != 'None':  #
        # if ('公益红娘群' in current_room_name or '心缘' in current_room_name or '公益单身男女相亲群' in current_room_name
        #         or '甬杭沪工作的爱心缘群' in current_room_name or '公益群' in current_room_name):
            # g_name='山有木兮木有枝'
            # g_name='天上闲人地上仙'
            # g_name='福玲家里'
            loop_random_info(my_room)
            actual_nick_name = msg['ActualNickName']
            actual_nick_name_req = re.search(r'丁文|浅水|张新梓|侠义|盈婷老师|陈菊芬13566075791|春天细雨|吴启浙|银凤|缘来是你|朱..萍|家电维修师傅|忻牡秀|蓝天(公益)|不收费|丽娜', actual_nick_name)
            if (record_txt(msg_text) and str(actual_nick_name_req) == 'None' and len(msg_text) > 80 and len(msg_text) < 350):
            # if (record_txt(msg_text)
            #         and '吴启浙' not in actual_nick_name and '中老年' not in actual_nick_name and '丁文' not in actual_nick_name
            #         and '浅水' not in actual_nick_name):
                msgCount = locale_txt["msgCount"]
                locale_txt["msgCount"] = msgCount + 1
                for room in my_room:
                    room_nick_name = room['NickName']
                    # if '天上闲人地上仙' == room_nick_name:
                    if '天上闲人地上仙' == room_nick_name and msgCount % 20 == 0:
                    # if ('山有木兮木有枝' in room_n880421 ick_name or '天上闲人地上仙' in room_nick_name) and len(msg_text) > 50:
                    # if '福玲家里' in room_nick_name and len(msg_text) > 50:
                        username = room['UserName']
                        # re_txt = "群聊: "+current_room_name + "\r\n" +actual_nick_name + ":\r\n" + msg_text
                        # re_txt = actual_nick_name + ":\r\n" + msg_text
                        re_txt = msg_text
                        # if 100101 > int(time.strftime("%H%M%S")) > 10101:  # 凌晨1点到上午10点  加叮嘱
                        #     re_txt = re_txt + '\r\n\r\n家人们, 请减少聊天, 让资料多多停留~~'
                        # if 92101 > int(time.strftime("%H%M%S")) > 10101:  # 凌晨1点到上午10点  加叮嘱
                        itchat.send_msg(re_txt, username)
                        # if 110101 > int(time.strftime("%H%M%S")) > 10101:  # 凌晨1点到上午11点  加叮嘱
                        #     itchat.send_msg('家人们, 请减少聊天, 让资料多多停留~~', username)
                    if '天上闲人地上仙资料' in room_nick_name:
                    # if '天上闲人地上仙资料' == room_nick_name:
                    # if ('山有木兮木有枝' in room_nick_name or '天上闲人地上仙' in room_nick_name) and len(msg_text) > 50:
                    # if '福玲家里' in room_nick_name and len(msg_text) > 50:
                        username = room['UserName']
                        # re_txt = "群聊: "+current_room_name + "\r\n" +actual_nick_name + ":\r\n" + msg_text
                        # re_txt = actual_nick_name + ":\r\n" + msg_text
                        re_txt = msg_text
                        # if 100101 > int(time.strftime("%H%M%S")) > 10101:  # 凌晨1点到上午10点  加叮嘱
                        #     re_txt = re_txt + '\r\n\r\n家人们, 请减少聊天, 让资料多多停留~~'
                        #if len(re_txt) < 350:
                        itchat.send_msg(re_txt, username)
                        # if 110101 > int(time.strftime("%H%M%S")) > 10101:  # 凌晨1点到上午11点  加叮嘱
                        #     itchat.send_msg('家人们, 请减少聊天, 让资料多多停留~~', username)

        # if '天上闲人地上仙' in current_room_name or '山有木兮木有枝' in current_room_name or '福玲家里' in current_room_name:
        #     for room in my_room:
        #         room_nick_name = room['NickName']
        #         # if '天上闲人地上仙' in room_nick_name:
        #         # if '山有木兮木有枝' in room_nick_name or '天上闲人地上仙' in room_nick_name or '福玲家里' in room_nick_name:
        #         # if '福玲家里' in room_nick_name:
        #         if current_room_name == room_nick_name:
        #             username = room['UserName']
        #             if msg['isAt']:                              #['IsAt']这个标签是TRUE说明有人@我
        #                 if '资料' in msg_text:
        #                     reply = appo_lists(msg_text)
        #                     for re_txt in reply:
        #                         itchat.send_msg(re_txt, username)
        #                         time.sleep(1.5)
        #                 else:
        #                     msg_text2 = msg_text
        #                     if '天上闲人地上仙' in current_room_name:
        #                         msg_text2 = msg_text2[14:200]
        #                     elif '福玲家里' in current_room_name:
        #                         msg_text2 = msg_text2[5:200]
        #                     elif '山有木兮木有枝' in current_room_name:
        #                         msg_text2 = msg_text2[14:200]
        #                     # context = get_info(msg_text2)         #青蜂侠
        #                     context = get_tuling_response(msg_text2)         #图灵
        #                     itchat.send_msg(context, username)       #发送信息
        #             # elif '所有人' in msg_text:                #判断是否发送的是群公告
        #             #     username = room['UserName']
        #                 # itchat.send_msg(context, username)
        #         # else:
        #         #     print('No groups found')


        # if '福玲家里' in current_room_name:
        #     # g_name='山有木兮木有枝'
        #     # g_name='天上闲人地上仙'
        #     # g_name='福玲家里'
        #     for room in my_room:
        #         room_nick_name = room['NickName']
        #         # if '天上闲人地上仙' in room['NickName']:
        #         # if '山有木兮木有枝' in room_nick_name or '天上闲人地上仙' in room_nick_name:
        #         if '福玲家里' in room_nick_name and len(msg_text)>20:
        #             username = room['UserName']
        #             actualNickName = msg['ActualNickName']
        #             re_txt = "消息来自于群聊: "+current_room_name + "\r\n" +actualNickName + ":\r\n" + msg_text
        #             itchat.send_msg(re_txt, username)
    except Exception as exceptionErr:
        print(exceptionErr, 11111111111111111111111111111111111111111111111)

@itchat.msg_register('Text', isFriendChat=True)
def text_reply(msg):
    from_user_name = msg['FromUserName']
    to_user_name = msg['ToUserName']
    # print("消息发送人", from_user_name)
    friends = itchat.get_friends(update=True)
    myUserName = friends[0]["UserName"]
    # autoReplyPerson = itchat.search_friends(name="周菜霞")[0]["UserName"]
    if from_user_name != myUserName:
    #     print("消息发送者是本人")
        return
    # if not from_user_name == autoReplyPerson:
    #     print("消息发送者不是需要自动回复的人")
    #     return
    msg_content = msg['Text']
    msg_content_reg = re.search(r'^--\d{1,}$', msg_content)
    if(msg_content == '--1'):
        re_txt = '网上聊聊可以的话, 男生多主动尽快约见面, 见面可以直观的了解对方 ' + '\r\n' +'第一次见面只喝饮料, 不浪费钱, 不喜欢可以早点走, 不用陪着吃完饭 ' \
                 + '\r\n' +'男生多主动约女生, 男生不主动, 女生可以找我继续介绍, 不用一直死等他' + '\r\n' +'女生不愿意配合男生见面, 男生可以找我再介绍, 没必要浪费时间精力,下一位更香 ' + '\r\n' \
                 +' ' + '\r\n' +'"双方通过好友", "约会后见面结果","没有意向联系对方了" ' + '\r\n' +'以上三个过程发生第一时间告知我, 我需要知道, 这样对双方都负责, ' + '\r\n' +'我也需要跟对方沟通的, 所以有结果了第一时间告知 ' + '\r\n' \
                 +' ' + '\r\n' +'希望你多来跟我沟通, 我既然做了这个事情了, 不会觉得你麻烦难弄, 你只管来找我介绍,没有回复你的话, 多问我几次,现在问我的人太多了 ' + '\r\n' +'如果领证了, 也请我喝个喜酒,发个红包,谢谢 ' + '\r\n'
        itchat.send_msg(re_txt, to_user_name)

    elif(msg_content_reg != None):
        # try:
        #     os.remove('./image/1.jpeg')
        #     os.remove('./image/2.jpeg')
        #     os.remove('./image/3.jpeg')
        # except Exception as e:
        #     print(e)
        try:
            infos = appo_info_by_code(msg_content[2:])
            itchat.send(infos['strs'], to_user_name)
            photoes2 = infos['photoes']
            photoes33 = photoes2.split(',')
            suffix = 'jpeg'
            for p in photoes33:
                aa = p.split(".")
                aaa = len(aa)
                suffix = aa[aaa - 1]

            c = 1
            for p in photoes33:
                IMAGE_URL = "https://fxappoj.gangcai.store:4334/api/nt/appo/appointments/" + p
                IMAGE_URL = quote(IMAGE_URL, safe=string.printable)
                pic_name= './image/{0}.{1}'.format(c, suffix)
                urllib.request.urlretrieve(IMAGE_URL, pic_name)  # 保存图片到本地，也可以用imurl来命名
                itchat.send_image(pic_name, to_user_name)
                c += 1
        except Exception as e:
            print(e)
            itchat.send("none", to_user_name)


def setDir(filepath):
    # filepath = './image'
    if not os.path.exists(filepath):
        os.mkdir(filepath)
    else:
        shutil.rmtree(filepath)
        os.mkdir(filepath)
setDir('./image')

itchat.auto_login(hotReload=True)  # 登录微信
itchat.run()

